package com.imd.s9.impl;


import com.alibaba.fastjson.JSONObject;
import com.imd.base.BusinessException;
import com.imd.s9.service.FeiShuService;
import com.imd.s9.util.FSmsg;
import com.imd.utils.FSApiUtil;
import com.imd.vo.s3.UserVO;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class FeiShuImpl implements FeiShuService {

    @Resource
    MongoTemplate mongoTemplate;
    @Resource
    FSmsg fSmsg;

    @Override
    public void testFSMsg(List<UserVO> users,String content,JSONObject... fields) throws BusinessException {
        for(UserVO uv:users){
            if (uv == null|| ObjectUtils.isEmpty(uv.getPhone())) throw new BusinessException(-1,"用户信息缺失");
            if(ObjectUtils.isEmpty(uv.getOpenId())){
                String openId = FSApiUtil.getOpenId(uv.getTenantId(),uv.getId());
                uv.setOpenId(openId);
                mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(new ObjectId(uv.getId()))), Update.update("openId", openId),"user");
            }
            JSONObject data = fSmsg.getMsg(content,fields);
            FSApiUtil.sendMsg(uv.getTenantId(), Arrays.asList(uv.getId()),data.toJSONString());
        }
    }

}
